<?php

class SiteController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index', 'view', 'create', 'update', 'votacion'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $this->redirect("index.php?r=site/votacion");
        $session = new CHttpSession;
        $session->open();

        $this->layout = 'login';
        $model = new LoginForm;
        // if it is ajax validation request
        /* if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
          {
          echo CActiveForm::validate($model);
          Yii::app()->end();
          } */

       
         
        // collect user input data
        if (isset($_POST['LoginForm'])) {

            $model->attributes = $_POST['LoginForm'];
            
            
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()):
                
               
                
                $this->redirect(array('Candidatos/Index'));
            else:
                $this->render('login', array('model' => $model));
            endif;
        } else {
            Yii::app()->user->logout();
            $this->render('login', array('model' => $model));
        }
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionAdmin() {
        $session = new CHttpSession;
        $session->open();

        $this->layout = 'login';
        $model = new LoginForm;
        // if it is ajax validation request
        /* if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
          {
          echo CActiveForm::validate($model);
          Yii::app()->end();
          } */

        // collect user input data
        if (isset($_POST['LoginForm'])) {

            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            
            if ($model->authenticateAdmin()):
                $this->redirect(array('candidatos/admin'));
            else:
                $this->render('loginAdmin', array('model' => $model));
            endif;
        } else {
            Yii::app()->user->logout();
            $this->render('loginAdmin', array('model' => $model));
        }
    }

    public function actionVotacion() {
        $session = new CHttpSession;
        $session->open();
        $this->layout = 'login';
        $model = new LoginForm;
//        //IF IT IS AJAX VALIDATION REQUEST
//        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form'):
//            echo CActiveForm::validate($model);
//            Yii::app()->end();
//        endif;
        //COLLECT USER INPUT DATA
        if (isset($_POST['LoginForm'])):
            $model->attributes = $_POST['LoginForm'];
            //VALIDATE USER INPUT AND REDIRECT TO THE PREVIOUS PAGE IF VALID       
            if ($model->dateValidation() && $model->authenticateVoting()):
                $this->redirect(array('votacion/elejirCandidato'));
            else:
                $this->render('loginVoting', array('model' => $model));
            endif;
        else:
            Yii::app()->user->logout();
            $this->render('loginVoting', array('model' => $model));
        endif;
    }
    
    public function actionInicio() {
        $this->render('index');
    }

    public function actionTimeOut() {
        $this->layout = 'main';
        $this->render('_timeOut');
    }

    public function actionVotoFisico() {
        $model = new LoginForm;
        //IF IT IS AJAX VALIDATION REQUEST
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form'):
            echo CActiveForm::validate($model);
            Yii::app()->end();
        endif;
        //COLLECT USER INPUT DATA
        if (isset($_POST['LoginForm'])):
            $model->attributes = $_POST['LoginForm'];
            //VALIDATE USER INPUT AND REDIRECT TO THE PREVIOUS PAGE IF VALID
            if ($model->validate() && $model->login()):
                $this->redirect(array('votacion/votoFisico'));
            endif;
        endif;
        //DISPLAY THE LOGIN FORM display the login form
        $this->layout = 'login';
        $this->render('login', array('model' => $model));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        $error = Yii::app()->errorHandler->error;
        if ($error):
            if (Yii::app()->request->isAjaxRequest):
                echo $error['message'];
            else:
                $this->render('error', $error);
            endif;
        endif;
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->subject) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                        "Reply-To: {$model->email}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-Type: text/plain; charset=UTF-8";

                mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(array('candidatos/index'));
        }
        // display the login form
        $this->layout = 'login';
        $this->render('login', array('model' => $model));
    }
    
    /**
     * Displays the login page
     */
    public function actionLoginAdmin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->loginAdmin())
                $this->redirect(array('candidatos/admin'));
        }
        // display the login form
        $this->render('loginAdmin', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        if(!Yii::app()->user->isGuest):
            $idProfile = Yii::app()->user->_idProfile;
            Yii::app()->user->logout();
            if ($idProfile == 0):
                $this->redirect('index.php?r=site/votacion');
            elseif ($idProfile == 1):
                $this->redirect('index.php?r=site/admin');
            else:
                $this->redirect('index.php?r=site/admin');
            endif;
        else:
            $this->redirect('index.php?r=site/votacion');
        endif;
        $idProfile = Yii::app()->user->_idProfile;
        Yii::app()->user->logout();
        if ($idProfile == 0):
            $this->redirect('index.php?r=site/votacion');
        elseif ($idProfile == 1):
            $this->redirect('index.php?r=site/admin');
        endif;
    }

}
